<?php
namespace app\index\controller;
header("Content-type: text/html; charset=utf-8");

use think\Controller;
use think\Session;
use Jssdk\JSSDK;
use WxpayAPI;

class Xjredbag extends Controller
{
    public function test(){
        echo md5('20180315');
    }


    public $hbname = "就行天下";
    public $body = "就行天下幸运九宫格";
    public $mch_id = "1316959901";
    public $wxappid = "wx45aaa00915e2fb58";
    public function data(){
        $arr['openid']='otDuzt2EfptFDxUxBzDKt1xEsN_U';
        $arr['hbname']="hbname";
        $arr['body']="body";
        $arr['fee']=1;
        $re = $this->sendhongbaoto($arr);
        dump($re);
    }

    public function sendhongbaoto($arr){
        $data['mch_id'] = $this->mch_id;
        $data['mch_billno'] = $this->mch_id.date("Ymd",time()).date("His",time()).rand(1111,9999);
        $data['nonce_str'] = self::createNoncestr();
        $data['re_openid'] = $arr['openid'];
        $data['wxappid'] = $this->wxappid;
        $data['nick_name'] = $arr['hbname'];
        $data['send_name'] = $arr['hbname'];
        $data['total_amount'] = $arr['fee']*100;
        $data['min_value'] = $arr['fee']*100;
        $data['max_value'] = $arr['fee']*100;
        $data['total_num'] = 1;
        $data['client_ip'] = $_SERVER['REMOTE_ADDR'];
        $data['act_name'] = 'act_name';
        $data['remark'] = 'remark';
        $data['wishing'] = $arr['body'];
        if(!$data['re_openid']) {
            $rearr['return_msg']='缺少用户openid';
            return $rearr;
        }
        $data['sign'] = self::getSign($data);
        $xml = self::arrayToXml($data);

        $url ="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
        $re = self::curlPost($url,$xml);
        $rearr = self::xmlToArray($re);
        return $rearr;
    }
    function trimString($value)
    {
        $ret = null;
        if (null != $value)
        {
            $ret = $value;
            if (strlen($ret) == 0)
            {
                $ret = null;
            }
        }
        return $ret;
    }
    /**
     * 作用：产生随机字符串，不长于32位
     */
    public function createNoncestr( $length = 32 )
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ ) {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
    /**
     * 作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }
    /**
     * 作用：生成签名
     */
    public function getSign($Obj)
    {
        foreach ($Obj as $k => $v)
        {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String."&key=65f8dac118c8d28d9df37b611dd81239"; // 商户后台设置的key
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }
    /**
     * 作用：array转xml
     */
    public function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val))
            {
                $xml.="<".$key.">".$val."</".$key.">";
            }
            else
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }
    /**
     * 作用：将xml转为array
     */
    public function xmlToArray($xml)
    {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

    public function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT,CERT.'/cert/apiclient_cert.pem');
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,CERT.'/cert/apiclient_key.pem');
        //第二种方式，两个文件合成一个.pem文件
//        curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}
?>